package com.zhfi.dataapply.config.quartz.risk;

import com.zhfi.dataapply.entity.data.po.risk.DishonestPO;
import com.zhfi.dataapply.mapper.risk.DishonestMapper;
import com.zhfi.dataapply.schedule.reader.risk.DishonestReader;
import com.zhfi.dataapply.schedule.writer.GeneralWriter;
import com.zhfi.dataapply.util.JobUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Slf4j
@Configuration
public class DishonestConfig implements JobExecutionListener {

    public static String JOB_NAME = "dishonest";

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobUtil jobUtil;

    @Autowired
    private DishonestReader reader;

    @Autowired
    private DishonestMapper mapper;

    @Bean
    public Job dishonestJob() {
        return jobBuilderFactory.get(JOB_NAME + "Job")
                .listener(this)
                .start(dishonestStep())
                .build();
    }

    @Bean
    public Step dishonestStep() {
        return stepBuilderFactory.get(JOB_NAME + "Step")
                .<DishonestPO, DishonestPO>chunk(20)
                .reader(reader)
                .writer(dishonestWriter())
                .build();
    }

    @Bean
    public ItemWriter<DishonestPO> dishonestWriter() {
        return new GeneralWriter<>(mapper);
    }

    @Override
    public void beforeJob(JobExecution jobExecution) {
        reader.reset();
        jobUtil.doJobStart(JOB_NAME);
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        jobUtil.doJobEnd(JOB_NAME, jobExecution);
    }

}